import angular from 'angular'
import '../../../public/js/plugins/select2/select2'
import util from '@yunke/core/util'
import '../../../public/js/myservice/contract/contract-common'
import myMath from '../../../public/js/myservice/common/my-math'
import {
    includes,
    reduce,
    chain,
    map,
    get,
    split,
    find
} from 'lodash'
import $ from 'jquery'

const markBadBebtConfimTpl = require('../../editinc/mark-bad-bebt-confim.html');

const apiPrefix = window.G_CONFIG.api_prefix; //api前缀

const ContractReceivableFund = angular.module('ContractReceivableFund', ['ContractCommonService']);

ContractReceivableFund
    .filter('signOrIncomeAmount', function () {
        return function (contract) {
            //云客签约-直属区域/云客签约-联营区域/云客直销
            //使用签约金额
            const limitContractArr = ['7f83719a-fce8-11e4-bed8-00155d02c832', '7f8422d0-fce8-11e4-bed8-00155d02c832', 'efa353cd-51ca-11e8-a035-00155d02c83e'];
            if (includes(limitContractArr, contract.contract_property_id)) {
                return contract.sign_amount;
            }
            return contract.income_amount ? contract.income_amount : 0;
        }
    })
    .filter('sumIncomeAmount', function () {
        return function (receivables) {
            return reduce(
                receivables,
                (acc, d) => d.__type === 'delete' ? acc : myMath.add(acc, d.receivable_amount),
                0
            )
        }
    })
    .filter('remainIncomeAmount2', function () {
        return function (receivables, contract) {
            const amount = reduce(receivables, (acc, d) => d.__type === 'delete' ? acc : myMath.add(acc, parseFloat(d.receivable_amount)), 0)
            const limitContractArr = ['7f83719a-fce8-11e4-bed8-00155d02c832', '7f8422d0-fce8-11e4-bed8-00155d02c832', 'efa353cd-51ca-11e8-a035-00155d02c83e'];
            return myMath.sub(contract[includes(limitContractArr, contract.contract_property_id) ? 'sign_amount' : 'income_amount'], amount)
        }
    })
    .controller('receivableModalCtrl', ["$scope", "contractId", "isSplit", "oldFund", "remainIncomeAmount", "contractCommonService", "$rootScope", "modalInstance",
        ($dialogScope, contractId, isSplit, oldFund, remainIncomeAmount, contractCommonService, $rootScope, modalInstance) => {
            /**
             * 打开款项编辑界面时初始化
             * oldFund: 原款项/被拆分款项
             * isSplit: 是否拆分（如果为true则oldFund为被拆分款项）
             * remainIncomeAmount: 应收金额最大限制
             */
            /*先处理下拉框数据*/
            //获取合同信息
            //获取合同信息
            $dialogScope.data = {}
            contractCommonService.getContract(contractId, function (data) {
                if (data) {
                    $dialogScope.contractBaseInfo = data.contract;
                    $dialogScope.$applyAsync();
                }
            });

            $dialogScope.maxIncomeAmount = remainIncomeAmount;

            //应收款名称下拉框
            $dialogScope.ddlConfigFundName = {
                allowClear: false,
                data: [],
                placeholder: '应收款名称'
            };
            contractCommonService.getReceivableFundName(function (data) {
                $dialogScope.ddlConfigFundName.data = map(data, d => ({
                    id: d.receivable_item_id,
                    text: d.receivable_item_name
                }))
                $dialogScope.$applyAsync();
            });

            //款项小类下拉框
            $dialogScope.ddlConfigFundSmallClass = {
                allowClear: false,
                data: [],
                placeholder: '款项小类'
            };
            contractCommonService.getFundSmallClass($dialogScope.contractBaseInfo.contract_property_id, function (data) {
                $dialogScope.$watch("data.fundInfo.receivable_item_id", (n) => {
                    if (n !== undefined) {
                        $dialogScope.ddlConfigFundSmallClass.data = chain(data)
                            .filter(
                                ({ receivable_item_id: receivableItemId, money_category_item_id: moneyCategoryItemId }) =>
                                    n === receivableItemId || moneyCategoryItemId === '4d17ed28-005a-11e5-bed8-00155d02c832' // 联营区域收入总是要显示
                            )
                            .map(d => ({
                                id: d.money_category_item_id,
                                text: d.money_category_item_name
                            }))
                            .value()
                        const moneyCategoryItemId = $dialogScope.data.fundInfo.money_category_item_id;
                        $dialogScope.data.fundInfo.money_category_item_id = find($dialogScope.ddlConfigFundSmallClass.data, ['id', moneyCategoryItemId]) ?
                            moneyCategoryItemId :
                            get($dialogScope.ddlConfigFundSmallClass.data, "0.id");
                    }
                })
            });

            //收入类别
            $dialogScope.ddlConfigIncomeCategory = {
                allowClear: false,
                data: [],
                placeholder: '核算收入类别',
                onchange2(newVal, scope) {
                    if (scope) {
                        scope.type_name = newVal.text;
                    }
                }
            };
            // 财务收项 选项
            $dialogScope.ddlConfigFinancial = {
                allowClear: false,
                data: [],
                placeholder: '核算收入类别',
                onchange2(newVal, scope) {
                    if (scope) {
                        scope.type_name = newVal.text;
                    }
                }
            };
            //获取核算收入类别下拉信息
            contractCommonService.getBussAccountTypes(function (data) {
                $dialogScope.ddlConfigIncomeCategory.data = map(data, d => ({
                    id: d.type_id,
                    text: d.type_name
                }));
                $dialogScope.ddlConfigFinancial.data = map(data, d => ({
                    id: d.type_id,
                    text: d.finance_type_name
                }));
                $dialogScope.$applyAsync();
            });
            //收款责任人下拉框
            $dialogScope.ddlConfigDutyOfficer = {
                ajax: {
                    url: apiPrefix + "erp-interface/get-users",
                    dataType: 'json',
                    delay: 250,
                    data(term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results(json) {
                        return {
                            results: json.retCode === "0" ? json.data : []
                        };
                    },
                    escapeMarkup(markup) {
                        return markup;
                    },
                    cache: true
                },
                minimumInputLength: 1,
                onchange2(newVal) {
                    $dialogScope.data.fundInfo.department_id = newVal.DepartmentId;
                    $dialogScope.data.fundInfo.department_name = newVal.DepartmentName;
                }
            };
            //收款责任人默认值  合同类型为云客签约-直属区域时
            if (oldFund == null && $dialogScope.contractBaseInfo.contract_property_id == "7f83719a-fce8-11e4-bed8-00155d02c832") {
                setTimeout(function () {
                    $('#idFundInfoPayeeId').data('select2').updateSelection({
                        id: $dialogScope.contractBaseInfo.sign_people_id,
                        text: $dialogScope.contractBaseInfo.sign_people_name
                    });
                    $dialogScope.data.fundInfo.payee_id = $dialogScope.contractBaseInfo.sign_people_id;
                }, 0);
                //获取用户信息 并设置
                if ($dialogScope.contractBaseInfo.sign_people_id != "") {
                    util.myAjax({
                        url: apiPrefix + "erp-interface/get-user&userGUID=" + $dialogScope.contractBaseInfo.sign_people_id,
                        type: "GET",
                        context: this,
                        success(json) {
                            if (json.retCode == 0) {
                                //收款责任人部门
                                if (json.data != null) {
                                    $dialogScope.data.fundInfo.department_id = json.data.DepartmentId;
                                    $dialogScope.data.fundInfo.department_name = json.data.DepartmentName;
                                }
                            } else {
                                util.alert("获取责任人部门失败：" + json.errMsg);
                            }
                        }
                    });
                }
            }

            //合同类型为联营签约-云客结算
            if (oldFund === null && $dialogScope.contractBaseInfo.contract_property_id === "7f856e81-fce8-11e4-bed8-00155d02c832") {
                const now = new Date();
                const nowY = now.getFullYear();
                const nowM = now.getMonth() + 1;
                const nowMM = (nowM > 9) ? nowM : ('0' + nowM);
                const nowD = now.getDate();
                const nowDD = (nowD > 9) ? nowD : ('0' + nowD);
                const formatNow = nowY + '-' + nowMM + '-' + nowDD;
                //责任人 默认为付小玲
                const fxlGUID = "a3c8f32d-374b-4772-95e9-0f3a84f2f1a1";
                setTimeout(function () {
                    //应收款名称
                    $('#idReceivableItemId').data('select2').updateSelection({
                        id: "882-fd02-11e4-bed8-00155d02c832",
                        text: "云客租用款"
                    });
                    $dialogScope.data.fundInfo.receivable_item_id = "882-fd02-11e4-bed8-00155d02c832";
                    //款项小类
                    $('#idMoneyCategoryItemId').data('select2').updateSelection({
                        id: "4d17ed28-005a-11e5-bed8-00155d02c832",
                        text: "联营区域收入"
                    });
                    $dialogScope.data.fundInfo.money_category_item_id = "4d17ed28-005a-11e5-bed8-00155d02c832";
                    //应收金额默认
                    $dialogScope.data.fundInfo.receivable_amount = $dialogScope.contractBaseInfo.income_amount;
                    //应收日期
                    $dialogScope.data.fundInfo.receivable_date = formatNow;
                    //付款条件
                    $dialogScope.data.fundInfo.payment_condition = "款到开通授权";

                    $('#idFundInfoPayeeId').data('select2').updateSelection({
                        id: fxlGUID,
                        text: "付小玲"
                    });
                    $dialogScope.data.fundInfo.payee_id = fxlGUID;
                }, 0);
                util.myAjax({
                    url: apiPrefix + "erp-interface/get-user&userGUID=" + fxlGUID,
                    type: "GET",
                    context: this,
                    success(json) {
                        if (json.retCode == 0) {
                            //收款责任人部门
                            if (json.data != null) {
                                $dialogScope.data.fundInfo.department_id = json.data.DepartmentId;
                                $dialogScope.data.fundInfo.department_name = json.data.DepartmentName;
                            }
                        } else {
                            util.alert("获取责任人部门失败：" + json.errMsg);
                        }
                    }
                });
            }

            //联合置业顾问
            $dialogScope.ddlConfigUniteSales = {
                ajax: {
                    url: apiPrefix + "erp-interface/get-users",
                    dataType: 'json',
                    delay: 250,
                    data(term) {
                        return {
                            keyword: term,
                            limit: 10
                        };
                    },
                    results(json) {
                        return {
                            results: json.retCode === "0" ? json.data : []
                        };
                    },
                    escapeMarkup(markup) {
                        return markup;
                    },
                    cache: true
                },
                minimumInputLength: 1,
                onchange2(newVal) {
                    $dialogScope.data.fundInfo.unite_sales_id = newVal.id;
                    $dialogScope.data.fundInfo.unite_sales_name = newVal.text;
                }
            };


            $dialogScope.orgianlFund = oldFund;
            $dialogScope.isSplit = isSplit;
            $dialogScope.data.fundInfo = angular.extend({}, oldFund, {
                contract_id: contractId
            });
            const arr = split($dialogScope.contractBaseInfo.attribute_name, ",")
            if (!$dialogScope.data.fundInfo.receivable_type) {
                $dialogScope.data.fundInfo.receivable_type = 1;
                //arr[0]代表新签，arr[1]代表混签，arr[2]代表续签，只有单独续签是true时receivable_type=2，其余情况为1
                if (arr[2] === 'true' && arr[0] !== 'true' && arr[1] !== 'true') {
                    $dialogScope.data.fundInfo.receivable_type = 2;
                } else {
                    $dialogScope.data.fundInfo.receivable_type = 1;
                }
            }
            if (isSplit && $dialogScope.data.fundInfo) {
                $dialogScope.data.fundInfo.old_receivable_id = $dialogScope.data.fundInfo.receivable_id;
                $dialogScope.data.fundInfo.receivable_id = null; //如果是拆分款项，则为新增模式
            }
            if (oldFund) {
                setTimeout(function () {
                    if (oldFund.unite_sales_name == null) {
                        oldFund.unite_sales_name = "";
                    }
                    if (oldFund.unite_sales_id == null) {
                        oldFund.unite_sales_id = "";
                    }
                    //$('.idReceivableId:last').data('select2').updateSelection({text: oldFund.receivable_item_name || oldFund.receivable_item_id});
                    $('.idDutyOfficer:last').data('select2').updateSelection({
                        text: oldFund.payee_name || oldFund.payee_id
                    });
                    $('.idUniteSales:last').data('select2').updateSelection({
                        text: oldFund.unite_sales_name || oldFund.unite_sales_id
                    });
                }, 0);
            } else {
                //获取收入
                contractCommonService.getContractRevenue(contractId, function (data) {
                    if (data && data.revenueList && data.revenueList.length > 0) {
                        $dialogScope.data.fundInfo.revenue_type = data.revenueList[0].revenue_type;
                        $rootScope.$applyAsync();
                    }
                });
            }

            contractCommonService.getContractReceivable(contractId, function (data) {
                /**
                 * 获取款项列表
                 */
                $dialogScope.editFunds = data;
                $dialogScope.$applyAsync();
            });
            $dialogScope.onSumbit = function () {
                const fundInfo = $dialogScope.data.fundInfo;
                //校验
                //如果是拆分模式，则应收金额必须小于被拆分款项
                if (isSplit && fundInfo.receivable_amount >= $dialogScope.orgianlFund.receivable_amount) {
                    util.alert('应收金额必须小于被拆分款项金额（' + $dialogScope.orgianlFund.receivable_amount + ')');
                    return false;
                }

                util.myAjax({
                    url: apiPrefix + (isSplit ? "/receivable/split-contract-receivalble" : "/receivable/save-contract-receivable"),
                    type: "POST",
                    context: this,
                    data: fundInfo,
                    success(json) {
                        if (json.retCode == 0) {
                            util.alert("保存成功");
                            modalInstance.resolve()
                        } else {
                            util.alert("保存失败：" + json.errMsg);
                        }
                    }
                });
            }
            $dialogScope.cancel = function () {
                modalInstance.reject()
            }
        }
    ])
    .service('receivableFundService', ['$rootScope', 'contractCommonService', function ($rootScope, contractCommonService) {
        $rootScope.fundInfo = {};
        $rootScope.editFunds = [];
        $rootScope.markBadBebtConfimTpl = markBadBebtConfimTpl;
        const service = {
            onFundEditChangePayeeShow($data, $dialog, $dialogScope, oldFund) {
                /**
                 * 打开款项变更责任人界面时初始化
                 * oldFund: 原款项
                 */
                $dialogScope.data.fundInfo = angular.extend({}, oldFund, {
                    contract_id: $data
                });
                //收款责任人下拉框
                $dialogScope.ddlConfigDutyOfficer = {
                    ajax: {
                        url: apiPrefix + "erp-interface/get-users",
                        dataType: 'json',
                        delay: 250,
                        data(term) {
                            return {
                                keyword: term,
                                limit: 10
                            };
                        },
                        results(json, page) {
                            var data = [];
                            if (json.retCode === "0") {
                                data = json.data;
                            }
                            return {
                                results: data
                            };
                        },
                        escapeMarkup(markup) {
                            return markup;
                        },
                        cache: true
                    },
                    minimumInputLength: 1,
                    onchange2(newVal) {
                        $dialogScope.data.fundInfo.department_id = newVal.DepartmentId;
                        $dialogScope.data.fundInfo.department_name = newVal.DepartmentName;
                    }
                };
                //联合置业顾问
                $dialogScope.ddlConfigUniteSales = {
                    ajax: {
                        url: apiPrefix + "erp-interface/get-users",
                        dataType: 'json',
                        delay: 250,
                        data(term) {
                            return {
                                keyword: term,
                                limit: 10
                            };
                        },
                        results(json, page) {
                            var data = [];
                            if (json.retCode === "0") {
                                data = json.data;
                            }
                            return {
                                results: data
                            };
                        },
                        escapeMarkup(markup) {
                            return markup;
                        },
                        cache: true
                    },
                    minimumInputLength: 1,
                    onchange2(newVal) {
                        //$dialogScope.data.fundInfo.unite_sales_id = newVal.DepartmentId;
                    }
                };

            },
            onFundEditChangeItemShow($data, $dialog, $dialogScope, oldFund) {
                $dialogScope.data.fundInfo = angular.extend({}, oldFund, {
                    contract_id: $data
                });
                $dialogScope.ddlConfigFundName = {
                    allowClear: false,
                    data: [],
                    placeholder: '应收款名称'
                };

                contractCommonService.getReceivableFundName(function (data) {
                    var ddlData = [];
                    $.each(data, function (i, d) {
                        ddlData.push({
                            id: d.receivable_item_id,
                            text: d.receivable_item_name
                        });
                    });
                    $dialogScope.ddlConfigFundName.data = ddlData;
                    $dialogScope.$applyAsync();
                });
            },
            onFundEditChangeRevenueTypeShow($data, $dialog, $dialogScope, oldFund) {
                $dialogScope.data.fundInfo = angular.extend({}, oldFund, {
                    contract_id: $data
                });
                //收入类别
                $dialogScope.ddlConfigIncomeCategory = {
                    allowClear: false,
                    data: [],
                    placeholder: '核算收入类别',
                    onchange2(newVal, scope) {
                        if (scope) {
                            scope.type_name = newVal.text;
                        }
                    }
                };
                $dialogScope.ddlConfigFinancial = {
                    allowClear: false,
                    data: [],
                    placeholder: '核算收入类别',
                    onchange2(newVal, scope) {
                        if (scope) {
                            scope.type_name = newVal.text;
                        }
                    }
                };
                //获取核算收入类别下拉信息
                contractCommonService.getBussAccountTypes(function (data) {
                    $dialogScope.ddlConfigIncomeCategory.data = map(
                        data,
                        ({ type_id, type_name }) => ({ id: type_id, text: type_name })
                    );
                    $dialogScope.ddlConfigFinancial.data = map(data, d => ({
                        id: d.type_id,
                        text: d.finance_type_name
                    }));
                    $dialogScope.$applyAsync();
                });
            },
            changeRevenueType($data, $dialog, $dialogScope, callback) {
                /**
                 * 变更责任人
                 */
                const fundInfo = $dialogScope.data.fundInfo;
                //校验
                if (fundInfo.revenue_type == fundInfo.revenue_type_new) {
                    util.alert('新关联收入项和原关联收入项相同');
                    return false;
                }
                fundInfo.revenue_type = fundInfo.revenue_type_new;
                util.myAjax({
                    url: apiPrefix + "/receivable/change-responsible-revenue-type",
                    type: "POST",
                    context: this,
                    data: fundInfo,
                    success(json) {
                        if (json.retCode == 0) {
                            util.alert("关联收入项变更成功");
                            if (callback) {
                                callback();
                            }
                        } else {
                            util.alert("关联收入项变更失败：" + json.errMsg);
                        }
                    }
                });
            },
            changeItem($data, $dialog, $dialogScope, callback) {
                /**
                 * 变更责任人
                 */
                var fundInfo = $dialogScope.data.fundInfo;
                //校验
                if (fundInfo.receivable_item_id == fundInfo.receivable_item_id_new) {
                    util.alert('新款项名称和原款项名称相同');
                    return false;
                }

                fundInfo.receivable_item_id = fundInfo.receivable_item_id_new;

                var post_data = fundInfo;
                var url;
                url = apiPrefix + "/receivable/change-responsible-item";

                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success(json) {
                        if (json.retCode == 0) {
                            util.alert("款项变更成功");
                            if (callback) {
                                callback();
                            }
                        } else {
                            util.alert("款项变更失败：" + json.errMsg);
                        }
                    }
                });
            },
            changePayee($data, $dialog, $dialogScope, callback) {
                /**
                 * 变更责任人
                 */
                var fundInfo = $dialogScope.data.fundInfo;
                //校验
                if (fundInfo.payee_id == fundInfo.payee_id_new) {
                    util.alert('新责任人和原责任人相同');
                    return false;
                }

                fundInfo.payee_id = fundInfo.payee_id_new;

                var post_data = fundInfo;
                var url;
                url = apiPrefix + "/receivable/change-responsible-person";

                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success(json) {
                        if (json.retCode == 0) {
                            util.alert("责任人变更成功");
                            if (callback) {
                                callback();
                            }
                        } else {
                            util.alert("责任人变更失败：" + json.errMsg);
                        }
                    }
                });
            },
            changeReceivableDate($data, $dialog, $dialogScope, callback) {
                /**
                 * 变更应收日期
                 */
                var fundInfo = $dialogScope.data.fundInfo;
                //校验
                if (fundInfo.receivable_date == $data.receivable_date_new) {
                    util.alert('新应收日期和原应收日期相同');
                    return false;
                }
                fundInfo.receivable_date = fundInfo.receivable_date_new;

                var post_data = fundInfo;
                var url;
                url = apiPrefix + "/receivable/change-receivable-date";

                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success(json) {
                        if (json.retCode == 0) {
                            util.alert("应收日期变更成功");
                            if (callback) {
                                callback();
                            }
                        } else {
                            util.alert("应收日期变更失败：" + json.errMsg);
                        }
                    }
                });
            },
            deleteFund(fundInfo) {
                /**
                 * 删除款项
                 */
                util.confirm('确定要删除此款项吗?', {
                    ok() {
                        var post_data = {
                            receivable_id: fundInfo.receivable_id
                        };
                        var url;
                        url = apiPrefix + "/receivable/delete-contract-receivable";

                        util.myAjax({
                            url: url,
                            type: "POST",
                            context: this,
                            data: post_data,
                            success(json) {
                                if (json.retCode == 0) {
                                    fundInfo.__isdelete = 1;
                                    util.alert("删除成功");
                                    $rootScope.$applyAsync();
                                } else {
                                    util.alert("删除失败：" + json.errMsg);
                                }
                            }
                        });
                    }
                });
            },
            markOperation(fundInfo, isOperation, callback) {
                /**
                 * 设置运营关注款
                 */
                var post_data = {
                    receivable_id: fundInfo.receivable_id,
                    is_operation: isOperation
                };
                var url;
                url = apiPrefix + "/receivable/mark-operation";

                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success(json) {
                        if (json.retCode == 0) {
                            if (callback) {
                                callback();
                            }
                            util.alert(isOperation ? "设置运营关注款成功" : "取消运营关注款成功");
                        } else {
                            util.alert((isOperation ? "设置运营关注款失败：" : "取消运营关注款失败：") + json.errMsg);
                        }
                    }
                });
            },
            markBadBebt(fundInfo, isBad, bad_debt_reason, callback) {
                /**
                 * 标记坏账
                 */
                var post_data = {
                    receivable_id: fundInfo.receivable_id,
                    is_bad_debt: isBad
                };
                if (bad_debt_reason) {
                    post_data['bad_debt_reason'] = bad_debt_reason;
                }
                var url;
                url = apiPrefix + "/receivable/mark-bad-debt";

                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    success(json) {
                        if (json.retCode == 0) {
                            if (callback) {
                                callback();
                            }
                            util.alert(isBad ? "标记为坏账成功" : "取消标记坏账成功");
                        } else {
                            util.alert((isBad ? "标记为坏账失败：" : "取消标记坏账失败：") + json.errMsg);
                        }
                    }
                });
            },
            markBadBebtConfim(fundInfo, isBad, bad_debt_reason, callback) {
                var that = this;
                if (isBad) {
                    that.markBadBebt(fundInfo, isBad, bad_debt_reason, callback);
                } else {
                    util.confirm('是否取消标记坏账', {
                        ok() {
                            that.markBadBebt(fundInfo, isBad, null, callback);
                        }
                    });
                }
            }
        };
        return service;
    }])
    .directive('receivableType', [() => {
        return {
            restrict: 'AE',
            require: 'ngModel',
            template: `<div class="col-sm-8 clearfix">
                <div class="checkbox fl" style="margin-right:50px">
                    <input type="checkbox" ng-model="receivable_type_1" ng-click='change()' id="rbt_new" name="customer_property">
                    <label for="rbt_new">新增</label>
                </div>
                <div class="checkbox fl" style="margin-right:50px">
                    <input type="checkbox" ng-model="receivable_type_3" ng-click='change()' id="rbt_continue" name="customer_property">
                    <label for="rbt_continue">续签</label>
                </div>
                <div class="checkbox fl">
                    <input type="checkbox" ng-model="receivable_type_2" ng-click='change()' id="rbt_increase" name="customer_property">
                    <label for="rbt_increase">增购</label>
                </div>
            </div>`,
            scope: {
                "model": "=ngModel"
            },
            controller: ['$scope', (s) => {
                s.$watch('model', (n) => {
                    if (n !== undefined) {
                        const values = String.prototype.split.call(n + '', ",")
                        s.receivable_type_1 = includes(values, '1')
                        s.receivable_type_2 = includes(values, '2')
                        s.receivable_type_3 = includes(values, '3')
                    }
                })

                function fb() {
                    const values = [
                        s.receivable_type_1 ? '1' : null,
                        s.receivable_type_2 ? '2' : null,
                        s.receivable_type_3 ? '3' : null
                    ]
                    s.model = chain(values).compact().join(',').value()
                }
                s.change = fb;
            }]
        };
    }]);

export default ContractReceivableFund;
